package com.demo.crm.springboot3security.controller;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.demo.crm.springboot3security.dto.FormDataRequest;
import com.demo.crm.springboot3security.dto.FormDataResponse;
import com.demo.crm.springboot3security.entity.CustomForm;
import com.demo.crm.springboot3security.mapper.CustomFormMapper;
import com.demo.crm.springboot3security.service.FormDataService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 表单数据控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/form-data")
@RequiredArgsConstructor
public class FormDataController {

    private final FormDataService formDataService;
    private final CustomFormMapper formMapper;

    /**
     * 保存表单数据
     */
    @PostMapping("/save")
    public ResponseEntity<FormDataResponse> saveFormData(@RequestBody FormDataRequest request) {
        try {
            CustomForm form = Optional.ofNullable(formMapper.selectOneWithFields(request.getFormId()))
                    .orElseThrow(() -> new RuntimeException("表单不存在"));
            Long recordId = formDataService.saveFormData(form, request.getData());
            return ResponseEntity.ok(FormDataResponse.success()
                    .setRecordId(recordId));
        } catch (Exception e) {
            log.error("保存表单数据失败", e);
            return ResponseEntity.ok(FormDataResponse.error(e.getMessage()));
        }
    }

    /**
     * 更新表单数据
     */
    @PutMapping("/update")
    public ResponseEntity<FormDataResponse> updateFormData(@RequestBody FormDataRequest request) {
        try {
            CustomForm form = Optional.ofNullable(formMapper.selectOneWithFields(request.getFormId()))
                    .orElseThrow(() -> new RuntimeException("表单不存在"));

            formDataService.updateFormData(form, request.getRecordId(), request.getData());
            return ResponseEntity.ok(FormDataResponse.success());
        } catch (Exception e) {
            log.error("更新表单数据失败", e);
            return ResponseEntity.ok(FormDataResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取表单数据
     */
    @GetMapping("/get/{formId}/{recordId}")
    public ResponseEntity<FormDataResponse> getFormData(@PathVariable Long formId, @PathVariable Long recordId) {
        try {
            CustomForm form = Optional.ofNullable(formMapper.selectOneWithFields(formId))
                    .orElseThrow(() -> new RuntimeException("表单不存在"));

            Map<String, Object> data = formDataService.getFormData(form, recordId);
            return ResponseEntity.ok(FormDataResponse.success()
                    .setData(data));
        } catch (Exception e) {
            log.error("获取表单数据失败", e);
            return ResponseEntity.ok(FormDataResponse.error(e.getMessage()));
        }
    }

    /**
     * 删除表单数据
     */
    @DeleteMapping("/delete/{formId}/{recordId}")
    public ResponseEntity<FormDataResponse> deleteFormData(@PathVariable Long formId, @PathVariable Long recordId) {
        try {
            CustomForm form = Optional.ofNullable(formMapper.selectOneWithFields(formId))
                    .orElseThrow(() -> new RuntimeException("表单不存在"));

            formDataService.deleteFormData(form, recordId);
            return ResponseEntity.ok(FormDataResponse.success());
        } catch (Exception e) {
            log.error("删除表单数据失败", e);
            return ResponseEntity.ok(FormDataResponse.error(e.getMessage()));
        }
    }

    /**
     * 查询表单数据
     */
    @PostMapping("/query")
    public ResponseEntity<FormDataResponse> queryFormData(@RequestBody FormDataRequest request) {
        try {
            CustomForm form = Optional.ofNullable(formMapper.selectOneWithFields(request.getFormId()))
                    .orElseThrow(() -> new RuntimeException("表单不存在"));

            List<Map<String, Object>> list = formDataService.queryFormData(
                    form,
                    request.getConditions(),
                    request.getPage(),
                    request.getSize());

            return ResponseEntity.ok(FormDataResponse.success()
                    .setList(list)
                    .setPage(request.getPage())
                    .setSize(request.getSize()));
        } catch (Exception e) {
            log.error("查询表单数据失败", e);
            return ResponseEntity.ok(FormDataResponse.error(e.getMessage()));
        }
    }
}